# -*- coding: utf-8 -*-
import json
import codecs
import pymysql
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


class ZhizhuPipeline(object):
    def __init__(self):
        self.file = codecs.open('../data.json','a',encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + '\n'
        print(line)
        self.file.write(line)
        return item

    def close_spider(self, spider):
        self.file.close()


class ZhizhuMysql(object):
    def __init__(self):
        self.cnn = pymysql.connect('192.168.116.128','root','123456','school')
        self.cursor = self.cnn.cursor()
        pass

    def process_item(self, item, spider):
        sql = """insert into news(title,info,content) values(%s,%s,%s)"""
        self.cursor.execute(sql,(item['title'],item['info'],item['article']))
        self.cnn.commit()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.cnn.close()